import type { Request } from 'express';
import { Brackets, In, Between } from 'typeorm';
import {
  responseSuccess,
  responseError,
  responseData,
} from '@/share/interface/standard';
import Base from '@/controller/public/MiniBaseController';

export class UserController extends Base {
  async test(req: Request) {
    const { phone = '' } = req.body;
    const user = await this.userRepository.findOne({
      where: { phone },
    });
    if (!user)
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });
    return responseSuccess(user);
  }
  async findBySearch(req: Request) {
    const {
      page = 1,
      limit = 10,
      gender,
      tag,
      nick_name,
    } = req.query;

    // 获取符合条件的用户 ID 列表，并进行分页
    const queryBuilder = this.userRepository
      .createQueryBuilder('user')
      .select([
        'user.id',
        'user.nick_name',
        'user.tag',
        'user.gender',
        'user.phone',
        'user.role',
        'user.age',
        'user.visit_list',
        'user.initial_dry_weight',
        'user.initial_resting_heart_rate',
      ])
      .leftJoinAndSelect('user.symptom', 'symptom')
      .leftJoinAndSelect('user.internal_health', 'internal_health')
      .leftJoinAndSelect('user.capacity_diary', 'capacity_diary')
      .where('user.delete = :delete', { delete: false })
      .orderBy('user.id', 'DESC');

    if (nick_name || tag || gender) {
      queryBuilder.andWhere(
        new Brackets((qb) => {
          if (nick_name) {
            qb.andWhere('user.nick_name LIKE :nick_name', {
              nick_name: `%${nick_name}%`,
            });
          }
          if (tag) {
            qb.andWhere('user.tag LIKE :tag', {
              tag: `%${tag}%`,
            });
          }
          if (gender) {
            // qb.andWhere('user.gender = :gender', {
            //   gender: +gender,
            // });
            qb.orWhere('user.gender IN (:...genders)', {
              genders: [+gender, 0], // 确保 gender 被处理为数字类型，并包含 0
            });
          }
        })
      );
    }

    const total = await queryBuilder.getCount();

    const skip: number = (+page - 1) * +limit;
    const users = await queryBuilder.skip(skip).take(limit).getMany();

    // 获取每个用户的最新7条daily_health记录
    for (const user of users) {
      const dailyHealthSubQuery = await this.dailyHealthRepository
        .createQueryBuilder('daily_health')
        .where('daily_health.user_id = :userId', { userId: user.id })
        .orderBy('daily_health.created', 'DESC')
        .limit(7)
        .getMany();
      user.daily_health = dailyHealthSubQuery;
    }

    return responseSuccess({
      result: users,
      page: +page,
      limit: +limit,
      total: +total,
    });
  }

  async findById(req: Request) {
    const id = parseInt(req.params.id) || req.user_id;

    // 子查询获取最新的7条daily_health记录
    const dailyHealthSubQuery = await this.dailyHealthRepository
      .createQueryBuilder('daily_health')
      .where('daily_health.user_id = :id', { id })
      .orderBy('daily_health.created', 'DESC')
      // .limit(7)
      .getMany();

    const user = await this.userRepository
      .createQueryBuilder('user')
      .leftJoinAndSelect('user.symptom', 'symptom')
      .where('user.id = :id', { id })
      .orderBy({
        'user.id': 'DESC',
      })
      .getOne();

    user.daily_health = dailyHealthSubQuery;

    if (!user) {
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });
    }

    return responseSuccess(user);
  }

  async addOrUpdate(req: Request) {
    const { nick_name, name, phone, gender, role, user_id } =
      req.body;
    // 构建用户对象
    const user = {
      ...req.body,
      id: user_id,
    };

    await this.userRepository.save(user);

    // await this.dailyHealthRepository.save({
    //   user: { id: user.id },
    // });
    const daily_health = new DailyHealthController();
    await daily_health.addDailyHealthForUser({
      ...req,
      body: { user_id },
    });
    return responseSuccess(user_id ? '更新用户成功' : '新增用户成功');
  }

  async updateBaseInfo(req: Request) {
    const {
      gender,
      age,
      phone,
      height,
      weight,
      diet,
      nick_name,
      user_id = req.user_id,
    } = req.body;
    if (isNaN(user_id)) {
      return responseError('无效的用户ID');
    }

    const user = await this.userRepository.findOne({
      where: { id: user_id },
    });
    if (!user)
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });

    await this.userRepository.save({
      ...req.body,
      id: user_id,
    });

    return responseSuccess();
  }
  // 给亲属填写手机并且更新关联患者信息
  async updatePhoneOfKinsfolk(req: Request) {
    const { phone, user_id = req.user_id } = req.body;
    if (isNaN(user_id)) {
      return responseError('无效的用户ID');
    }
    if (!phone) return responseError('请输入手机号');

    const user = await this.userRepository.findOne({
      where: { id: user_id },
    });

    const relation = await this.relationShipRepository.find({
      where: { phone },
    });

    if (!relation.length) {
      return responseData({
        code: 2,
        msg: '该手机号未被关联,请在患者端关联',
        data: '',
      });
    }

    await this.userRepository.save({
      ...user,
      phone,
      relation_ship: relation.map((rel) => ({
        ...rel,
        users: rel.user, // 亲属绑定患者的信息
      })),
    });
    return responseSuccess('关联成功');
  }
  async remove(req: Request) {
    const id = parseInt(req.params.id);
    let userToRemove = await this.userRepository.findOneBy({ id });
    if (!userToRemove) {
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });
    }
    await this.userRepository.remove(userToRemove);
    return responseSuccess('用户删除成功');
  }
}
export class SymptomController extends Base {
  // 获取症状
  async findAll() {
    const symptoms = await this.symptomRepository.find({
      where: {
        id: Between(1, 7), // 使用 Between 来指定 ID 范围
      },
    });
    return responseSuccess(symptoms);
  }

  async addSymptom(req: Request) {
    const { name } = req.body;
    await this.symptomRepository.save({
      name,
    });
    return responseSuccess('新增症状成功');
  }

  async updateSymptomForUser(req: Request) {
    let { symptom_ids, name, user_id = req.user_id } = req.body;

    if (isNaN(user_id)) {
      return responseError('无效的用户ID');
    }

    const user = await this.userRepository.findOne({
      where: { id: user_id },
      relations: ['symptom'],
    });
    if (!user)
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });

    // 如果传了一个新的name，则添加至症状列表中
    if (name) {
      let symptom = await this.symptomRepository.findOne({
        where: { name },
      });
      let new_symptom;
      if (!symptom) {
        new_symptom = await this.symptomRepository.save(
          this.symptomRepository.create({ name })
        );
      }
      symptom_ids = [...symptom_ids, new_symptom?.id ?? symptom.id];
    }

    // 查找所有给定 ID 的症状
    const symptoms_list = await this.symptomRepository.find({
      where: { id: In(symptom_ids) },
    });
    // const symptoms_list_ids = symptoms_list.map(
    //   (symptom) => symptom.id
    // );
    // if (symptoms_list_ids.length !== symptom_ids.length) {
    //   return responseError('含不存在的症状');
    // }

    // 将症状添加到用户的症状列表中
    // user.symptom = symptoms_list;
    // 保存用户

    await this.userRepository.save({
      id: user.id,
      symptom: symptoms_list,
    });
    return responseSuccess('保存成功');
  }
  // 删除症状
  async removeSymptom(req: Request) {
    const { name } = req.body;
    if (!name) return responseError('缺少症状名称');
    const symptom = await this.symptomRepository.findOne({
      where: { name },
    });
    if (!symptom) return responseError('症状不存在');
    await this.symptomRepository.delete(symptom);
    return responseSuccess('删除成功');
  }
}
export class DailyHealthController extends Base {
  async addDailyHealthForUser(req: Request) {
    const {
      id,
      user_id = req.user_id,
      today_weight, // 今日体重
      // resting_heart_rate, // 静息心率
      today_blood_pressure, // 血压
      today_hypotension, // 低血压
      today_resting_heart_rate, // 静息心率
      // dry_weight, // 干体质量
      // today_status, // 今日状态
      today_inability_to_lie_flat, // 不能平卧的程度
      today_shortness_of_breath, // 呼吸困难的程度
      today_fatigue, // 疲乏的程度
      today_lower_limb_swelling, // 下肢水肿的程度
      today_thirst, // 口渴的程度
      today_abdominal_distension, // 腹胀的程度
      today_poor_appetite, // 食欲不振的程度
      remarks, // 备注,
      // 用来判断表单提交
      form_submit = 0,
    } = req.body;

    // console.log(req.body, '-----');
    if (isNaN(user_id)) {
      return responseError('无效的用户ID');
    }
    const user = await this.userRepository.findOne({
      where: { id: user_id },
      relations: ['daily_health'],
    });

    if (!user)
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });

    const health = this.dailyHealthRepository
      .createQueryBuilder('health')
      .leftJoinAndSelect('health.user', 'user')
      .where('user.id = :user_id', { user_id })
      .orderBy('health.created', 'DESC');

    const health_records = await health.getMany();

    let today = health_records.find((record) => {
      const recordDate = new Date(record.created);
      const todayDate = new Date();
      return (
        recordDate.getFullYear() === todayDate.getFullYear() &&
        recordDate.getMonth() === todayDate.getMonth() &&
        recordDate.getDate() === todayDate.getDate()
      );
    });

    console.log(today, 'today');

    let is_normal_status = [
      today_inability_to_lie_flat,
      today_shortness_of_breath,
      today_fatigue,
      today_lower_limb_swelling,
      today_thirst,
      today_abdominal_distension,
      today_poor_appetite,
    ].some((symptom) => symptom == 1);

    const healthData = this.dailyHealthRepository.create({
      remarks,
      today_weight,
      today_resting_heart_rate,
      today_blood_pressure,
      today_hypotension,
      today_inability_to_lie_flat,
      today_shortness_of_breath,
      today_fatigue,
      today_lower_limb_swelling,
      today_thirst,
      today_abdominal_distension,
      today_poor_appetite,
    });
    // 表单处才判断 status，status 只是判断是否有异常症状的
    if (form_submit === 1) {
      healthData.today_status = is_normal_status ? 1 : 0;
      healthData.today_submit = 1;
    }

    if (id) {
      // 修改后台的
      await this.dailyHealthRepository.save({
        ...healthData,
        id,
        user: { id: user.id },
      });
      return responseSuccess();
    }
    // 今日有数据时这里是修改今日数据的
    if (today) {
      await this.dailyHealthRepository.update(
        { id: today.id },
        healthData
      );
      return responseSuccess();
    }

    // 这里是创建的
    await this.dailyHealthRepository.save({
      ...healthData,
      user: { id: user.id },
    });

    return responseSuccess();
  }

  /*   async submitFormStatus(req: Request) {
    const user_id = req.user_id;
    const {
      today_inability_to_lie_flat, // 不能平卧的程度
      today_shortness_of_breath, // 呼吸困难的程度
      today_fatigue, // 疲乏的程度
      today_lower_limb_swelling, // 下肢水肿的程度
      today_thirst, // 口渴的程度
      today_abdominal_distension, // 腹胀的程度
      today_poor_appetite, // 食欲不振的程度
    } = req.body;
    const user = await this.userRepository.findOne({
      where: { id: user_id },
    });
    if (!user) return responseData({code: 201,msg: '用户不存在',data: null});

    const is_normal_status = [
      today_inability_to_lie_flat,
      today_shortness_of_breath,
      today_fatigue,
      today_lower_limb_swelling,
      today_thirst,
      today_abdominal_distension,
      today_poor_appetite,
    ].some((symptom) => symptom == 1);

    const data = {
      today_status: is_normal_status ? 1 : 0,
      today_inability_to_lie_flat,
      today_shortness_of_breath,
      today_fatigue,
      today_lower_limb_swelling,
      today_thirst,
      today_abdominal_distension,
      today_poor_appetite,
      today_submit: 1,
    };

    const health = this.dailyHealthRepository
      .createQueryBuilder('health')
      .leftJoinAndSelect('health.user', 'user')
      .where('user.id = :user_id', { user_id })
      .orderBy('health.created', 'DESC');

    const health_records = await health.getMany();

    let today = health_records.find(
      (record) =>
        new Date(record.created).getDate() === new Date().getDate()
    );

    if (today) {
      await this.dailyHealthRepository.update({ id: today.id }, data);
      await this.dailyHealthRepository.save({
        ...data,
        user: { id: user_id },
      });

      return responseSuccess();
    }
    return responseSuccess();
  } */
  async delDailyHealthForUser(req: Request) {
    const { id } = req.query;
    await this.dailyHealthRepository.delete(id);
    return responseSuccess();
  }
}
export class InternalHealthController extends Base {
  /**
   * 更新用户疾病史
   */
  async updateInternalHealthForUser(req: Request) {
    const {
      heart_failure_type, // 心衰类型
      heart_function_grade, // 心功能等级
      medication_history, // 药物史
      surgical_history, // 手术史
      hospitalizations, // 住院次数
      user_id = req.user_id,
    } = req.body;
    if (isNaN(user_id)) {
      return responseError('无效的用户ID');
    }
    const user = await this.userRepository.findOne({
      where: { id: user_id },
    });
    if (!user)
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });

    // await this.internalHealthRepository.save({
    //   heart_failure_type,
    //   heart_function_grade,
    //   medication_history,
    //   surgical_history,
    //   hospitalizations,
    //   user,
    // });
    await this.internalHealthRepository.upsert(
      {
        heart_failure_type,
        heart_function_grade,
        medication_history,
        surgical_history,
        hospitalizations,
        user,
      },
      ['user']
    );

    return responseSuccess();
  }
}
export class RelationShipController extends Base {
  async addRelation(req: Request) {
    const {
      relation,
      check_me_permission,
      phone,
      user_id = req.user_id,
    } = req.body;
    if (!user_id) {
      return responseError('无效的用户ID');
    }
    if (!phone) return responseError('请输入手机号');
    const cur_user = await this.userRepository.findOne({
      where: { id: user_id },
    });
    const rel_user = await this.userRepository.findOne({
      where: { phone: phone },
    });
    if (!cur_user) {
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });
    }

    let cur_relation_ship = await this.relationShipRepository.findOne(
      {
        where: { patient_id: user_id, phone: phone },
      }
    );

    if (cur_relation_ship) {
      return responseError('该手机号已被关联');
    }

    cur_relation_ship = this.relationShipRepository.create({
      phone,
      relation,
      patient_id: user_id,
      check_me_permission,
      user: [rel_user],
    });

    // if (!relation_ship.user) {
    //   relation_ship.user = [];
    // }
    // relation_ship.user.push(user);
    await this.relationShipRepository.save(cur_relation_ship);

    return responseSuccess(cur_relation_ship);
  }
  async removeRelation(req: Request) {
    const { phone, user_id = req.user_id } = req.body;

    if (!user_id) {
      return responseError('无效的用户ID');
    }
    if (!phone) return responseError('请输入手机号');

    // 获取用户和关联用户信息
    // const user = await this.userRepository.findOne({
    //   where: { id: user_id },
    // });
    // const order_user = await this.userRepository.findOne({
    //   where: { phone },
    // });

    // 检查用户和关联用户是否存在
    // if (!user || !order_user) {
    //   return responseError('关联用户不存在');
    // }

    // 获取现有的关系记录
    let relation_ship = await this.relationShipRepository.findOne({
      where: { user: { id: user_id }, phone },
    });

    // 检查关系是否存在
    if (!relation_ship) {
      return responseError('关系不存在');
    }

    // 删除关系记录
    await this.relationShipRepository.remove(relation_ship);

    return responseSuccess('取消关联用户成功');
  }
  // 获取亲属下的所有患者用户关系和数据
  async getAllRelationListForUser(req: Request) {
    const user_id = req.user_id;
    const user = await this.userRepository.findOne({
      where: { id: user_id },
    });
    // 患者
    if (user.role === 'patient') {
      // 返回绑定的关联信息
      const relation = await this.relationShipRepository.find({
        where: { patient_id: user_id },
      });
      return responseSuccess(relation);
    }
    // 亲属返回患者信息
    const relation = await this.relationShipRepository.find({
      // 这里绑定了需要亲属调登录接口才会有关联数据，所以查不出来，按照手机号来查
      // where: { user: { id: user_id } },
      where: { phone: user.phone },
      select: [
        'patient_id',
        'phone',
        'relation',
        'check_me_permission',
      ],
      relations: ['user'],
    });
    const patient_ids = relation
      .filter((rel) => rel.patient_id)
      .map((rel) => rel.patient_id);
    const patients_info = await this.userRepository.find({
      where: { id: In(patient_ids) },
      relations: [
        'daily_health',
        'internal_health',
        'symptom',
        'capacity_diary',
      ],
      order: {
        daily_health: {
          created: 'DESC',
        },
      },
    });
    return responseSuccess(patients_info);
  }
}
export class ModuleClickController extends Base {
  async findAll() {
    const module_click = await this.moduleClickRepository.find({
      relations: ['user'],
    });
    return responseSuccess(module_click);
  }
  async getModuleClickCountForUser(req: Request) {
    const user_id = parseInt(req.params.id);
    const user = await this.userRepository.findOne({
      where: { id: user_id },
    });
    if (!user) {
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });
    }
    const module = await this.moduleClickRepository.find({
      where: { user: { id: user_id } },
      //   relations: ['user'],
    });
    return responseSuccess(module);
  }
  async moduleClickForUser(req: Request) {
    const { user_id, module_name } = req.body;
    if (isNaN(user_id)) {
      return responseError('无效的用户ID');
    }
    const user = await this.userRepository.findOne({
      where: { id: user_id },
    });
    if (!user) {
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });
    }

    const module = await this.moduleClickRepository.findOne({
      where: { module_name, user: { id: user_id } },
    });

    if (module) {
      // 对应模块的 module_visit + 1
      this.moduleClickRepository.update(module.id, {
        module_visit: module.module_visit + 1,
      });
      return responseSuccess('更新模块点击');
    }

    await this.moduleClickRepository.save({
      user,
      module_name,
    });

    return responseSuccess('新增模块点击');
  }
  async remoteModuleClickForUser(req: Request) {
    const { user_id, module_name } = req.body;
    if (isNaN(user_id)) {
      return responseError('无效的用户ID');
    }
    const user = await this.userRepository.findOne({
      where: { id: user_id },
    });
    if (!user) {
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });
    }

    const module = await this.moduleClickRepository.findOne({
      where: { user: { id: user_id }, module_name },
    });

    if (!module) return responseError('模块不存在');
    await this.moduleClickRepository.delete({
      module_name,
      id: module.id,
    });

    return responseSuccess('删除模块成功');
  }
}

export class RoleController extends Base {
  async findAll() {
    const role = await this.roleRepository.find();
    return responseSuccess(role);
  }
}
